package com.chen.demo.chater2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping(value="/users")
public class UserController {
	
	static Map<Long, Users> usersMap = Collections.synchronizedMap(new HashMap<Long,Users>());
	
	@RequestMapping(value="/",method=RequestMethod.GET)
	public List<Users> getUserList(){
		//还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
		List<Users> rList = new ArrayList<Users>(usersMap.values());
		return rList;
	}
	@RequestMapping(value="/",method=RequestMethod.POST)
	public String postUser(@ModelAttribute Users users){
		usersMap.put(users.getId(), users);
//		System.out.println(usersMap.get("1").getName());
		//除了@ModelAttribute绑定参数之外，还可以通过@RequestParam从页面中传递参数
		return "success";
	}
	@RequestMapping(value="/{id}",method=RequestMethod.GET)
	public Users getUsers(@PathVariable Long id){
		// url中的id可通过@PathVariable绑定到函数的参数中
		return usersMap.get(id);
	}
	@RequestMapping(value="/{id}",method=RequestMethod.DELETE)
	public String deleteUser(@PathVariable Long id){
		try {
			usersMap.remove(id);
			return "success";
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "fail";
		}
	}
}
